import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/loginsso', '/exposurePreview', '/serviceportal/home', '/serviceportal/projectList', '/serviceportal/supervise', '/serviceportal/supervise', '/serviceportal/exposure', '/serviceportal/ProjectListDetails']

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    // 有token
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.getters.routes.length === 0 && whiteList.indexOf(to.path) === -1) {
        // 判断当前用户是否已拉取完路由信息
        store.dispatch('GenerateRoutes').then(accessRoutes => {
          // 根据roles权限生成可访问的路由表
          router.addRoutes(accessRoutes) // 动态添加可访问路由表
          next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
        }).catch(() => {
          store.dispatch('LogOut').then(() => {
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      // 否则全部重定向到登录页
      window.location.href = `${process.env.VUE_APP_CALLBACK_URL}`
      // next(`/login?redirect=${to.fullPath}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
